<?php

namespace common\wechat\service;

use think\Db;
use common\wechat\model\WechatAccessTokenModel;
use common\wechat\model\WechatUserModel;
use think\Config;
use common\user\service\PostService as userRegister;
use common\user\model\UserModel;
use common\user\model\ThirdPartyUserModel;
use common\user\logic\infoLogic as info;

class ApiService {

    /**
     * 更新token
     */
    public function up_oauth($data = '', $type = '') {
        if (empty($data)) {
            return FALSE;
        }
        if (empty($type)) {
            $config = cmf_is_wechat() ? Config::get('wechat.Official') : Config::get('wechat.Web');
            $scope = cmf_is_wechat() ? 'snsapi_userinfo' : 'snsapi_login';
        } else {
            $config = Config::get('wechat.' . $type);
            $scope = 'snsapi_userinfo';
        }

        // 补充参数
        $data['expire_time'] = time() + $data['expires_in'];
        $data['app_id'] = $config['appid'];
        $WechatAccessTokenModel = new WechatAccessTokenModel();
        $where = [];
        $where['app_id'] = $config['appid'];
        $where['openid'] = $data['openid'];
        if (isset($data['unionid']) && !empty($data['unionid'])) {
            $where['unionid'] = $data['unionid'];
        }
        if ($data['scope'] != 'snsapi_base,snsapi_userinfo,') {
            $where['scope'] = $data['scope'];
//            $oauth = $WechatAccessTokenModel->where($where)->find()->toarray();
            $oauth = $WechatAccessTokenModel->where($where)->find();
            if (empty($oauth)) {
                $WechatAccessTokenModel->data($data)->isUpdate(false)->allowField(true)->save();
            } else {
                $oauth = $oauth->toarray();
                $data['id'] = $oauth['id'];
                $WechatAccessTokenModel->isUpdate(true)->allowField(true)->save($data);
            }
        } else {
            unset($data['scope']);
            $WechatAccessTokenModel->allowField(true)->save($data, $where);
        }



        return $data;
    }

    // 获取oauth数组信息
    public function get_oauth($openid = '', $type = '') {
        // 需要查询一次用户信息
        if (empty($type)) {
            $config = cmf_is_wechat() ? Config::get('wechat.Official') : Config::get('wechat.Web');
            $scope = cmf_is_wechat() ? 'snsapi_userinfo' : 'snsapi_login';
        } else {
            $config = Config::get('wechat.' . $type);
            $scope = 'snsapi_userinfo';
        }

        $WechatAccessTokenModel = new WechatAccessTokenModel();
        $where = [];
        $where['app_id'] = $config['appid'];
        $where['openid'] = $openid;
        $where['scope'] = $scope;

        $oauth_info = $WechatAccessTokenModel->where($where)->find();
        if (!empty($oauth_info)) {
            // SDK实例对象
//            $oauth = &load_wechat('Oauth');
            $oauth = new \WeChat\Oauth($config);
            // 判断是否超时
            if ($oauth_info['expire_time'] < time()) {
                $result = $oauth->getOauthRefreshToken($oauth_info['refresh_token']);
                // 严重超期,不可用
                if ($result === FALSE) {
                    return false;
                } else {
                    // 更新oauth信息
                    self::up_oauth($result);
                    return $result;
                }
            } else {
                return $oauth_info->toarray();
            }
        }
        return false;
    }

    // 获取用户信息
    public function get_wx_info($openid = '', $request = object, $type = '', $more = []) {
        $oauth_info = self::get_oauth($openid, $type);

        if ($oauth_info === FALSE) {
            return FALSE;
        }

//        $oauth = &load_wechat('Oauth');
//        $config = Config::get('wechat');
        if (empty($type)) {
            $config = cmf_is_wechat() ? Config::get('wechat.Official') : Config::get('wechat.Web');
        } else {
            $config = Config::get('wechat.' . $type);
        }

        $oauth = new \WeChat\Oauth($config);
        // 检查token是否还有效
        // 执行接口操作
//        $OauthUserinfo = $oauth->getOauthUserinfo($oauth_info['access_token'], $openid);
        if (empty($more)) {
            $OauthUserinfo = $oauth->getUserInfo($oauth_info['access_token'], $openid);
        } else {
            $OauthUserinfo = $more;
            if (empty($OauthUserinfo)) {
                $OauthUserinfo = FALSE;
            }
        }

        $where = [];
        $where['app_id'] = $config['appid'];
        $where['openid'] = $openid;
        if (!empty($oauth_info['unionid'])) {
            $where['union_id'] = $oauth_info['unionid'];
        }
        $UserWx = new info();
        // 处理返回结果
        if ($OauthUserinfo === FALSE) {
            // 接口失败的处理
            // 
            // 静默登录无法获取用户信息
            $UserWxInfo = $UserWx->info($where);
            if (empty($UserWxInfo)) {
                return FALSE;
            }

            $UserWxInfo['app_id'] = $config['appid'];
            //强制设置访问类型为1
            $UserWxInfo['type'] = 1;
            $UserWxInfo['deviceType'] = config('third_sns_type')[$UserWxInfo['type']];
            if (!empty($oauth_info['unionid'])) {
                $UserWxInfo['union_id'] = $oauth_info['unionid'];
            }
            return $UserWxInfo;
        } else {
            // 接口成功的处理
            // 需要判断是否已经入库过.
            // 判断是否以前存过,如果存过要判断是否要更新
            $UserWxInfo = $UserWx->info($where);
            if (empty($UserWxInfo)) {
                //加入必要参数
                $request->get(['openid' => $openid]);
                $request->get(['unionid' => $oauth_info['unionid']]);
                $request->get(['sex' => $OauthUserinfo['sex']]);
                $request->get(['nickname' => $OauthUserinfo['nickname']]);
                $request->get(['headimgurl' => $OauthUserinfo['headimgurl']]);
                $request->get(['expire_time' => $oauth_info['expire_time']]);
                $request->get(['last_login_ip' => $request->ip(0, TRUE)]);
                $request->get(['openid' => $openid]);
                $request->get(['unionid' => $oauth_info['unionid']]);
                $request->get(['type' => 1]);
                // 需要绑定用户
                $userRegister = new userRegister();
                $userRegister->Register_third($request, $type);
                $data = $OauthUserinfo;
                $data['app_id'] = $config['appid'];
                $data['unionid'] = $oauth_info['unionid'];
                $data['type'] = 1;
                $data['deviceType'] = config('third_sns_type')[$data['type']];
                $UserWxModel = new WechatUserModel();
                $UserWxModel->data($data)->isUpdate(false)->allowField(true)->save();
                return $data;
            } else {
                //有注册过微信帐号信息,说明以前注册过,但需要注意是否有更新过部分信息
                $OauthUserinfo['id'] = $UserWxInfo['id'];
                $OauthUserinfo['app_id'] = $config['appid'];
                $OauthUserinfo['type'] = 1;
                $OauthUserinfo['deviceType'] = config('third_sns_type')[$OauthUserinfo['type']];
                if (!empty($oauth_info['unionid'])) {
                    $OauthUserinfo['union_id'] = $oauth_info['unionid'];
                }
                $userRegister = new userRegister();
                $userRegister->edit_third($OauthUserinfo);
                return $OauthUserinfo;
            }
        }
    }

    //更新第三方用户信息
}
